package com.oscar.ehome.view.setview;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.SDKInitializer;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.utils.DistanceUtil;
import com.google.gson.Gson;
import com.oscar.ehome.R;
import com.oscar.ehome.base.BaseBean;
import com.oscar.ehome.base.C;
import com.oscar.ehome.base.activity.BasesActivity;
import com.oscar.ehome.bean.UsersBean;
import com.oscar.ehome.bean.loginbean.UserBean;
import com.oscar.ehome.bean.setbean.SginMessageBean;
import com.oscar.ehome.presenter.SetPresenter;
import com.oscar.ehome.provider.baiduMap.MyLocationListener;
import com.oscar.ehome.provider.gildeimage.GildeUtils;
import com.oscar.ehome.utils.basethem.TintManager;
import com.oscar.ehome.utils.system.SystemConfigFactory;
import com.oscar.ehome.utils.util.CommonUtils;
import com.oscar.ehome.utils.util.ToastUtil;
import com.oscar.ehome.utils.view.MyImageView;
import com.oscar.ehome.view.loginview.LoginActivity;
import com.oscar.ehome.view.loginview.SubmitActivity;
import com.oscar.ehome.view.messageview.MessageDetilActivity;
import com.oscar.ehome.view.pageview.AddMemberActivity;
import com.oscar.ehome.view.setview.view.SginDakaView;

import org.apache.commons.collections.MapUtils;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import pub.devrel.easypermissions.AppSettingsDialog;
import pub.devrel.easypermissions.EasyPermissions;

/**
 * Created by xielinke on 2017/7/22.
 * 签到页面
 */

public class SigninActivity extends BasesActivity<SginDakaView, SetPresenter> implements MyLocationListener.MyCallBack, SginDakaView, EasyPermissions.PermissionCallbacks {

    /**
     * 返回
     */
    @BindView(R.id.title_img_back)
    ImageView titleImgBack;
    /**
     * 返回
     */
    @BindView(R.id.title_layout_left)
    RelativeLayout titleLayoutLeft;
    /**
     * 标题
     */
    @BindView(R.id.title_topbar)
    TextView titleTopbar;
    /**
     * 统计
     */
    @BindView(R.id.title_img_right)
    ImageView titleImgRight;
    /**
     * 统计
     */
    @BindView(R.id.title_right_layput)
    RelativeLayout titleRightLayput;
    /**
     * 头像
     */
    @BindView(R.id.sgin_img)
    MyImageView sginImg;
    /**
     * 姓名
     */
    @BindView(R.id.sign_name)
    TextView signName;
    /**
     * 职级
     */
    @BindView(R.id.sign_leve)
    TextView signLeve;
    /**
     * 时间
     */
    @BindView(R.id.sign_daka_time)
    TextView sign_daka_time;

    /**
     * 时间
     */
    @BindView(R.id.sign_dao_time)
    TextView signDaoTime;

    /**
     * 地址
     */
    @BindView(R.id.sgin_adrss)
    TextView sginAdrss;
    /**
     * 签到布局
     */
    @BindView(R.id.sign_dao_layout)
    LinearLayout signDaoLayout;
    /**
     * 签退时间
     */
    @BindView(R.id.sign_tui_time)
    TextView signTuiTime;
    /**
     * 地址
     */
    @BindView(R.id.sgin_tuiadrss)
    TextView sginTuiadrss;
    /**
     * 签退布局
     */
    @BindView(R.id.sign_tui_layout)
    LinearLayout signTuiLayout;
    /**
     * 打卡
     */
    @BindView(R.id.sign_buton)
    ImageView signButon;
    /**
     * 打卡文字
     */
    @BindView(R.id.sign_daka_text)
    TextView signDakaText;
    /**
     * 公司
     */
    @BindView(R.id.sgin_sdress_company)
    TextView sginSdressCompany;

    /**
     * 是否正确
     */
    @BindView(R.id.sgin_adress_right)
    ImageView sgin_adress_right;
    /**
     * 定位地址布局
     */
    @BindView(R.id.sgin_daka_adresslayout)
    RelativeLayout sginDakaAdresslayout;

    /**
     * 打卡布局
     */
    @BindView(R.id.daka_layout)
    RelativeLayout dakaLayout;
    /**
     * title布局
     */
    @BindView(R.id.basetitle_bar)
    RelativeLayout basetitleBar;

    /**
     * 地址图标
     */
    @BindView(R.id.sgin_adrss_img)
    ImageView sgin_adrss_img;
    /**
     * 地址图标
     */
    @BindView(R.id.sgin_tuiadrss_img)
    ImageView sgin_tuiadrss_img;

    //map
    public LocationClient mLocationClient = null;
    public BDLocationListener myListener;

    SetPresenter presenter;
    String token = "";
    String adress = "";//地址
    LatLng latLng2;
    double mDistance;
    int dingwei = 0;//是否定位成功

    SginMessageBean sginMessageBean;
    SginMessageBean.CheckBean checkBean;

    String moningStatus = "";//签到
    String getAfternoonEndTime = "";//签退

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sgnin);
        ButterKnife.bind(this);
        isPressmion();
        setColor();
        initMap();
        initView();
        init();
        initData();
        new TimeThread().start(); //启动新的线程
        new AdressThread().start();
    }

    /**
     * 设置颜色
     */
    public void setColor() {

        basetitleBar.setBackgroundColor(Color.parseColor(SystemConfigFactory.getInstance(SigninActivity.this).getSystemConfig().getColor()));
        TintManager.setTint(signButon, Color.parseColor(SystemConfigFactory.getInstance(this).getSystemConfig().getColor()));
        TintManager.setTint(sgin_adrss_img, Color.parseColor(SystemConfigFactory.getInstance(this).getSystemConfig().getColor()));
        TintManager.setTint(sgin_tuiadrss_img, Color.parseColor(SystemConfigFactory.getInstance(this).getSystemConfig().getColor()));
    }

    /**
     * 页面初始化
     */
    public void initView() {
        titleImgBack.setImageResource(R.mipmap.fanhui);
        titleImgBack.setVisibility(View.VISIBLE);
        titleTopbar.setText("签到");
        titleImgRight.setImageResource(R.mipmap.zhiji);
        titleRightLayput.setVisibility(View.VISIBLE);

        token = SystemConfigFactory.getInstance(this).getSystemConfig().getToken();
    }

    /**
     * 初始数据
     */
    public void init() {

        String users = SystemConfigFactory.getInstance(SigninActivity.this).getSystemConfig().getUserMessage();
        UsersBean userBe = null;
        if (users != null) {
            userBe = new Gson().fromJson(users, UsersBean.class);
        }
        if (userBe != null) {
            if (userBe.getName() != null) {
                signName.setText(userBe.getName());
            } else {
                if (SystemConfigFactory.getInstance(SigninActivity.this).getSystemConfig().getUsername() != null) {
                    signName.setText(SystemConfigFactory.getInstance(SigninActivity.this).getSystemConfig().getUsername());
                }
            }
            if (userBe.getRoleMobile() != null) {
                signLeve.setText(userBe.getRoleMobile().getRoleName());
            } else {
                signLeve.setText(getString(R.string.nodata));
            }
            if (userBe.getPhoto() != null) {
                String img_path = userBe.getPhoto();
//                GildeUtils.imgLoadPic(SigninActivity.this, C.qiniu_ip + img_path, sginImg, "net-p");
                GildeUtils.loadUrlImage4(C.qiniu_ip + img_path, sginImg, SigninActivity.this);
            } else {
                if (SystemConfigFactory.getInstance(SigninActivity.this).getSystemConfig().getUserimg() != null) {
                    String img_path = SystemConfigFactory.getInstance(SigninActivity.this).getSystemConfig().getUserimg();
//                    GildeUtils.imgLoadPic(SigninActivity.this, C.qiniu_ip + img_path, sginImg, "net-p");
                    GildeUtils.loadUrlImage4(C.qiniu_ip + img_path, sginImg, SigninActivity.this);
                }
            }

        }

        signDaoLayout.setVisibility(View.GONE);
        signTuiLayout.setVisibility(View.GONE);
        dakaLayout.setVisibility(View.GONE);
        sginDakaAdresslayout.setVisibility(View.GONE);
    }

    public void initMap() {
        //百度地图／
        //初始化
        SDKInitializer.initialize(getApplicationContext());
        myListener = new MyLocationListener(this);
        mLocationClient = new LocationClient(getApplicationContext());
        //声明LocationClient类
        mLocationClient.registerLocationListener(myListener);
        //注册监听函数
        initLocation();
        //定位
        mLocationClient.start();
    }

    /**
     * 加载数据
     */
    public void initData() {
        presenter.getSginMessage(token);
    }

    /**
     * 打卡
     */
    public void setDaka() {
        if (MapUtils.getObject(CommonUtils.dakaMap, "lon") != null && MapUtils.getObject(CommonUtils.dakaMap, "lat") != null) {
            String lats = String.valueOf(MapUtils.getObject(CommonUtils.dakaMap, "lat"));
            String lons = String.valueOf(MapUtils.getObject(CommonUtils.dakaMap, "lon"));
            presenter.setDaka(token, lons, lats, adress);
        } else {
            presenter.setDaka(token, "0", "0", adress);
        }
    }

    @OnClick({R.id.title_layout_left, R.id.title_right_layput, R.id.daka_layout})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.title_layout_left:
                finish();
                break;
            case R.id.title_right_layput:
                Intent intent = new Intent(SigninActivity.this, SiginCountActivity.class);
                intent.putExtra("sgin", 2);
                startActivity(intent);
                break;
            case R.id.daka_layout:
                setDaka();
                break;
        }
    }

    /**
     * 是否允许定位
     */
    public void isPressmion() {
        if (Build.VERSION.SDK_INT >= 23) {//、获取手机状态：
            String[] perms = {Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.READ_PHONE_STATE};
            if (EasyPermissions.hasPermissions(this, perms)) {//检查是否获取该权限
            } else {
                //第二个参数是被拒绝后再次申请该权限的解释
                //第三个参数是请求码
                //第四个参数是要申请的权限
                EasyPermissions.requestPermissions(this, "开启位置权限！", 0, perms);
            }
        }
    }

    private void initLocation() {
        LocationClientOption option = new LocationClientOption();

        option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);
        //可选，默认高精度，设置定位模式，高精度，低功耗，仅设备

        option.setCoorType("bd09ll");
        //可选，默认gcj02，设置返回的定位结果坐标系

        int span = 3000;
        option.setScanSpan(span);
        //可选，默认0，即仅定位一次，设置发起定位请求的间隔需要大于等于1000ms才是有效的

        option.setIsNeedAddress(true);
        //可选，设置是否需要地址信息，默认不需要

        option.setOpenGps(true);
        //可选，默认false,设置是否使用gps

        option.setLocationNotify(true);
        //可选，默认false，设置是否当GPS有效时按照1S/1次频率输出GPS结果

        option.setIsNeedLocationDescribe(true);
        //可选，默认false，设置是否需要位置语义化结果，可以在BDLocation.getLocationDescribe里得到，结果类似于“在北京天安门附近”

        option.setIsNeedLocationPoiList(true);
        //可选，默认false，设置是否需要POI结果，可以在BDLocation.getPoiList里得到

        option.setIgnoreKillProcess(false);
        //可选，默认true，定位SDK内部是一个SERVICE，并放到了独立进程，设置是否在stop的时候杀死这个进程，默认不杀死

        option.SetIgnoreCacheException(false);
        //可选，默认false，设置是否收集CRASH信息，默认收集

        option.setEnableSimulateGps(false);
        //可选，默认false，设置是否需要过滤GPS仿真结果，默认需要

        mLocationClient.setLocOption(option);
    }

    @Override
    public void sendAdd(String add) {
//        ToastUtil.show(this, "add" + add);
    }

    @Override
    public void sendLatLong(double lat, double lon, String address) {
        LatLng latLng1 = new LatLng(lat, lon);
        mDistance = DistanceUtil.getDistance(latLng1, latLng2);
        Log.e("452163", "sendLatLong: "+mDistance );
        if (mDistance < 1) {
            mDistance = 100000;
        }

        CommonUtils.dakaMap.put("lat", lat);
        CommonUtils.dakaMap.put("lon", lon);
        CommonUtils.dakaMap.put("mDistance", mDistance);
    }

    @Override
    public void sendResult(String result) {
//        ToastUtil.show(this, result);
    }

    @Override
    public void sendErry(String result) {
        if (dingwei == 2) {
            dingwei = 3;
            ToastUtil.show(this, result);
            mDistance = 100000;//设置一个假数据
        }
    }

    /**
     * 获取打卡信息
     *
     * @param sginchuqinBean
     */
    @Override
    public void getSginMessage(SginMessageBean sginchuqinBean) {
        dingwei = 2;
        if (sginchuqinBean != null) {
            sginMessageBean = new SginMessageBean();
            sginMessageBean = sginchuqinBean;
            initLoaction();
        }
    }

    /**
     * 判断是否打卡以及是否在定位范围内
     */
    public void initLoaction() {

        //多地点打卡 遍历集合  进行判断
        checkBean = sginMessageBean.getCheckwork();
        adress = checkBean.getPositionName();
        if ("2".equals(sginMessageBean.getAfternoonStatus())) {//全部打卡,展示打卡信息
            moningStatus = "0";
            getAfternoonEndTime = "0";

            signDaoLayout.setVisibility(View.VISIBLE);
            signTuiLayout.setVisibility(View.VISIBLE);
            dakaLayout.setVisibility(View.GONE);
            sginDakaAdresslayout.setVisibility(View.GONE);
            signDaoTime.setText(sginMessageBean.getMoningStartTime());
            sginAdrss.setText(sginMessageBean.getMoningInfo());
            signTuiTime.setText(sginMessageBean.getAfternoonEndTime());
            sginTuiadrss.setText(sginMessageBean.getAfternoonInfo());
        } else {
            if ("1".equals(sginMessageBean.getMoningStatus())) {//签到卡
                moningStatus = sginMessageBean.getMoningStatus();
                dakaLayout.setVisibility(View.VISIBLE);
                signDakaText.setText("签到打卡");
                sginDakaAdresslayout.setVisibility(View.GONE);
                latLng2 = new LatLng(Double.valueOf(checkBean.getPositionY()), Double.valueOf(checkBean.getPositionX()));
                if (mDistance < Double.valueOf(checkBean.getPositionError())) {//在考勤范围内
                    sginDakaAdresslayout.setVisibility(View.VISIBLE);
                    sgin_adress_right.setImageResource(R.mipmap.cha);
                    sginSdressCompany.setText("正在定位");
                } else {
                    sginDakaAdresslayout.setVisibility(View.VISIBLE);
                    sgin_adress_right.setImageResource(R.mipmap.cha);
                    sginSdressCompany.setText("正在定位");
                }
            } else {//签退卡
                getAfternoonEndTime = checkBean.getAfternoonEndTime();
                if ("1".equals(checkBean.getAfternoonEndTime())) {
                    signDaoLayout.setVisibility(View.VISIBLE);
                    signDaoTime.setText(sginMessageBean.getMoningStartTime());
                    sginAdrss.setText(sginMessageBean.getMoningInfo());

                    dakaLayout.setVisibility(View.VISIBLE);
                    signDakaText.setText("签退打卡");
                    sginDakaAdresslayout.setVisibility(View.GONE);
                    latLng2 = new LatLng(Double.valueOf(checkBean.getPositionY()), Double.valueOf(checkBean.getPositionX()));
                    if (mDistance < Double.valueOf(checkBean.getPositionError())) {//在考勤范围内
                        sginDakaAdresslayout.setVisibility(View.VISIBLE);
                        sgin_adress_right.setImageResource(R.mipmap.cha);
                        sginSdressCompany.setText("正在定位");
                    } else {
                        sginDakaAdresslayout.setVisibility(View.VISIBLE);
                        sgin_adress_right.setImageResource(R.mipmap.cha);
                        sginSdressCompany.setText("正在定位");
                    }
                }
            }
        }
    }

    /**
     * 更新定位范围内打卡状态
     */
    public void setLoaction() {
        if (!"0".equals(moningStatus) && !"0".equals(getAfternoonEndTime)) {
            if ("1".equals(moningStatus) || "1".equals(getAfternoonEndTime)) {
                if (mDistance < Double.valueOf(checkBean.getPositionError())) {//在考勤范围内
                    sginSdressCompany.setText("您已进入考勤范围" + "(" + adress + ")" + "内");
                    sgin_adress_right.setImageResource(R.mipmap.queding);
                } else {
                    sginSdressCompany.setText("您不在考勤范围" + "(" + adress + ")" + "内");
                    sgin_adress_right.setImageResource(R.mipmap.cha);
                }
            }
        }
    }


    /**
     * 打卡状态
     *
     * @param result
     */
    @Override
    public void setSgin(String result) {
        ToastUtil.show(this, result);
        initData();
    }

    @Override
    public void erroy() {
        dismissLoading();
        ToastUtil.show(this, "请求失败，请检查权限");
    }

    @Override
    public void erry(String result) {
        dismissLoading();
        ToastUtil.show(this, result);
        if (result.contains("过期")) {
            this.getSharedPreferences("appbase", Context.MODE_PRIVATE).edit().clear().commit();
            SystemConfigFactory.getInstance(this).getSystemConfig().SetLogin(false);
            SystemConfigFactory.getInstance(this).getSystemConfig().setIsFirst(true);
            Intent intent = new Intent(this, LoginActivity.class);
            startActivity(intent);
            finish();
        }
    }

    @Override
    public void onPermissionsGranted(int requestCode, List<String> perms) {

    }

    @Override
    public void onPermissionsDenied(int requestCode, List<String> perms) {
        if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
            new AppSettingsDialog.Builder(this, "为了您能正常打卡，请开启位置权限！")
                    .setTitle("提示")
                    .setPositiveButton("去设置")
                    .setNegativeButton("取消", null)
                    .setRequestCode(0)
                    .build()
                    .show();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    /***
     * 时间handler
     */
    class TimeThread extends Thread {
        @Override
        public void run() {
            do {
                try {
                    Thread.sleep(1000);
                    Message msg = new Message();
                    msg.what = 1;  //消息(一个整型值)
                    mHandler.sendMessage(msg);// 每隔1秒发送一个msg给mHandler
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            } while (true);
        }
    }

    /**
     * 定时更新位置信息
     */
    class AdressThread extends Thread {
        @Override
        public void run() {
            do {
                try {
                    Thread.sleep(3000);
                    Message msg = new Message();
                    msg.what = 2;  //消息(一个整型值)
                    mHandler.sendMessage(msg);// 每隔1秒发送一个msg给mHandler
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            } while (true);
        }
    }

    //在主线程里面处理消息并更新UI界面
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    long sysTime = System.currentTimeMillis();//获取系统时间
                    //时间显示格式
                    CharSequence sysTimeStr = DateFormat.format("hh:mm:ss", sysTime);
                    sign_daka_time.setText(sysTimeStr);
                    break;
                case 2:
                    if (sginMessageBean != null && sginMessageBean.getAfternoonStatus() != null) {
                        if (!"2".equals(sginMessageBean.getAfternoonStatus())) {//全部打卡,展示打卡信息
                            setLoaction();
                        }
                    }
                    break;
                default:
                    break;
            }
        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mLocationClient.stop();
        if (mHandler != null) {
            mHandler.removeMessages(1);
            mHandler.removeMessages(2);
//            mHandler.removeCallbacksAndMessages(null);
//            mHandler = null;
        }
    }

    @Override
    protected SetPresenter createPresenter() {
        presenter = new SetPresenter(this);
        return presenter;
    }
}
